package com.ssl.commonutils;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;

import java.io.*;
import java.util.UUID;

/**
 * 描述：pdf工具类
 *
 * @author ssl
 * @create 2017/12/12 11:09
 */
public class PdfUtils {

    public static byte[] fileToPdf(String docPath) throws Exception {
        byte[] docBuf = IOUtils.toByteArray(new FileInputStream(docPath));
        return fileToPdf(docBuf);
    }

    public static byte[] fileToPdf(byte[] docBuf) throws Exception {
        byte[] pdfBuf = null;
        File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
        String fileName = UUID.randomUUID().toString();
        File fileDoc = new File(tempDirectory.getAbsolutePath() + File.separator + fileName + ".doc");
        File filePdf = new File(tempDirectory.getAbsolutePath() + File.separator + fileName + ".pdf");
        System.out.println(filePdf.getPath());
        IOUtils.write(docBuf, new FileOutputStream(fileDoc));
        String command = "soffice";
        if (SystemUtils.IS_OS_MAC_OSX) {
            command = "/Applications/LibreOffice.app/Contents/MacOS/soffice";
        } else if (SystemUtils.IS_OS_WINDOWS) {
            command = "soffice";
        }
        CommandResult commandResult = CommandUtils.execute(command, "--headless", "--convert-to",
                "pdf:writer_pdf_Export", "--outdir", System.getProperty("java.io.tmpdir"),
                fileDoc.getAbsolutePath());
        if (commandResult.getRet() == 0) {
            if (filePdf.exists() && filePdf.length() > 0) {
                pdfBuf = new byte[(int) filePdf.length()];
                IOUtils.readFully(new FileInputStream(filePdf), pdfBuf);
                // 删除临时文件
                FileWriter fw;
                try {
                    fw = new FileWriter(fileDoc);
                    fw.write("");
                    fw.close();
                    fileDoc.delete();

                    fw = new FileWriter(filePdf);
                    fw.write("");
                    fw.close();
                    filePdf.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return pdfBuf;
            } else {
                String output = commandResult.getOutput();
                System.out.println(commandResult.getCommand() + "\r\n" + output);
                throw new IOException(output);
            }
        } else {
            System.out.println(commandResult.getIOException());
            throw commandResult.getIOException();
        }
    }

    /**
     * 文件(word，excel，图片等)转pdf
     *
     * @param filePath 文件完整路径(包含文件名),eg:<br>c:/file/doc/1.doc
     * @param pdfPath  存放pdf文件的路径,eg:<br>c:/file/pdf
     * @return
     * @throws IOException
     */
    public static String fileToPdf(String filePath, String pdfPath) throws IOException {
        /** 获取文件名 */
        File file = new File(filePath);
        String fileName = FilenameUtils.getBaseName(filePath) + ".pdf";
        File pdfFile = new File(pdfPath, fileName);
        /** 定义执行命令语句 */
        String command = "soffice";
        if (SystemUtils.IS_OS_MAC_OSX) {
            command = "/Applications/LibreOffice.app/Contents/MacOS/soffice";
        } else if (SystemUtils.IS_OS_WINDOWS) {
            command = "soffice";
        }
        CommandResult commandResult = CommandUtils.execute(command, "--headless", "--convert-to",
                "pdf:writer_pdf_Export", "--outdir", pdfPath, file.getAbsolutePath());
        if (commandResult.getRet() == 0) {
            if (pdfFile.exists() && pdfFile.length() > 0) {
                /** 转为pdf成功 */
                return pdfFile.getPath();
            } else {
                String output = commandResult.getOutput();
                System.out.println(commandResult.getCommand() + "\r\n" + output);
                throw new IOException(output);
            }
        } else {
            System.out.println(commandResult.getIOException());
            throw commandResult.getIOException();
        }
    }

    public static void main(String[] args) {
        String filePath = "F:\\libreoffice\\file\\1.doc";
        String pdfPath = "F:\\libreoffice\\file";
        try {
            pdfPath = fileToPdf(filePath, pdfPath);
            System.out.println(pdfPath);
            //byte[] pdfbuf = fileToPdf(filePath);
            //FileUtils.writeByteArrayToFile(new File("C:\\Users\\49383\\Desktop\\工作\\pp22.pdf"), pdfbuf);
            System.out.println("success!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
